package com.example.mine_platform.controller;

import com.example.mine_platform.commom.Result;
import com.example.mine_platform.config.JwtUtils;
import com.example.mine_platform.pojo.dto.UserLoginDTO;
import com.example.mine_platform.pojo.dto.UserRegisterDTO;
import com.example.mine_platform.pojo.entities.User;
import com.example.mine_platform.pojo.vo.UserLoginVO;
import com.example.mine_platform.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class LoginController {
    @Resource
    UserService userService;
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录，{}", userLoginDTO);
        User user = userService.login(userLoginDTO);

        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("phone", user.getPhone());
        claims.put("level",user.getLevel());
        String token = JwtUtils.createJWT(claims);

        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setLevel(user.getLevel());
        userLoginVO.setUserName(user.getUserName());
        userLoginVO.setToken(token);
        return Result.success(userLoginVO);
    }
    @PostMapping("/register")
    public Result register(@RequestBody UserRegisterDTO userRegisterDTO){
        log.info("用户注册：{}",userRegisterDTO);
        userService.register(userRegisterDTO);
        return Result.success();
    }
}
